<template>
  <div class="page-list-live">
    <PageList>
      <template #header>单位组织管理</template>
      <!-- 表单搜索 -->
      <template #filter>
        <ListFilter :form="topFilter" @search="search" @reset="handleReset" />
      </template>
      <template v-if="adminObj.IsSupper" #tips>
        <el-button icon="el-icon-document-add" type="primary" class="box" @click="handleAdd">新增建设单位</el-button>
      </template>
      <template #table>
        <ListTable ref="clientTable" :lazy="true" :loading="tableLoading" :table-data="tableData" :table-col="tableCol" @loadHandler="loadHandler">
          <template slot="col1" slot-scope="scope">
            <el-button :loading="scope.row.loadingDel" size="mini" icon="el-icon-edit" style="padding: 0px" type="text" @click="handleAdd(scope.row, true, false)">新增子部门</el-button>
            <el-button :loading="scope.row.loadingDel" size="mini" icon="el-icon-edit" style="padding: 0px" type="text" @click="handleRowEdit(scope.row)">编辑</el-button>
            <el-button :loading="scope.row.loadingDel" size="mini" icon="el-icon-delete" type="text" style="color: red; padding: 0px" @click="handleRowDel(scope.row)">删除</el-button>
          </template>
          <template slot="col2" slot-scope="scope">
            <span style="min-width: 600px; display: inline-block; text-align: left">{{ scope.row.roleName }}</span>
          </template>
        </ListTable>
      </template>
    </PageList>
    <AddRole ref="AddRole" @getList="getList" @reloadParent="reloadParent" />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import listMixin from '@/mixins/list'
import ListFilter from '@/components/ListFilter'
import { RoleSearch, RoleDel } from '@/api/Role'
import AddRole from './components/AddRole'

export default {
  components: {
    ListFilter,
    AddRole
  },

  mixins: [listMixin],

  data() {
    return {
      loadData: [],
      loadmap: new Map(),
      selectedParentId: 0,
      topFilter: {
        roleName: {
          label: '上级部门',
          placeholder: '请输入上级部门'
        }
        // gongdian: {
        //   label: '工点',
        //   placeholder: '请输入用户部门',
        //   type: 'select',
        //   arr: []
        // },
        // keyword: {
        //   label: '关键字',
        //   placeholder: '请输入员工编码或姓名、RFID、门禁卡'
        // }
      },
      tableData: [],
      tableCol: [
        // { type: 'index', label: '序号', width: '160px' },
        { prop: 'roleName', label: '上级部门', custom: 'col2' },
        { label: '操作', custom: 'col1' }
      ]
    }
  },
  computed: {
    ...mapGetters(['adminObj'])
  },
  methods: {
    loadHandler: async function (tree, treeNode, resolve) {
      this.loadmap.set(tree.id, { tree, treeNode, resolve })
      var loadingItems = await this.getByParentId(tree.id)
      console.info(loadingItems)
      resolve(loadingItems)
    },
    handleAdd(row, isChild, isEdit) {
      console.info('row', row)
      this.$refs['AddRole'].open(row, isChild, isEdit)
      var roles = []
      var menunId = row.parentId
      if (isChild) {
        row.parentName = row.roleName
        roles = row.menuRoles.map((item) => item.menuId)
        menunId = row.id
      }
      this.$refs['AddRole'].getMenuList2(menunId, roles)
    },
    async handleRowEdit(row) {
      // 设置编辑模式
      await this.$store.dispatch('user/setEdit', {
        status: true,
        id: row.id
      })
      var isChild = false
      var roles = []
      if (row.parentId !== 0) {
        isChild = true
        var parentModel = this.loadData.filter((r) => r.id === row.parentId)[0]
        if (parentModel === undefined) {
          parentModel = row.parentRole
        }

        console.info('parentModel', parentModel)

        if (parentModel === undefined || parentModel === null) {
          const obj = {
            pageIndex: 1,
            pageSize: 10,
            search: []
          }
          obj.search.push({
            key: 'parentId',
            value: 0,
            operation: 0
          })

          const {
            data: { items }
          } = await RoleSearch(obj)

          parentModel = items[0]
        }
        row.parentName = parentModel.roleName
        roles = parentModel.menuRoles.map((item) => item.menuId)
      }
      this.$refs['AddRole'].open(row, isChild, true)
      console.info(row)
      this.$refs['AddRole'].getMenuList2(row.parentId, roles)
    },
    async reloadParent(parentId) {
      if (parentId !== 0) {
        if (this.loadmap.get(parentId)) {
          var { resolve } = this.loadmap.get(parentId)
          var items = await this.getByParentId(parentId)
          this.$set(this.$refs.clientTable.$refs.listClientTable.store.states.lazyTreeNodeMap, parentId, [])
          resolve(items)
        }
      }
    },
    async delRowReq(row) {
      try {
        const obj = { id: row.id, value: null }
        await RoleDel(obj)
        // row.loadingDel = false
        await this.getList()
        await this.reloadParent(row.parentId)
        this.$message({
          type: 'success',
          message: '删除成功'
        })
      } catch (err) {
        // row.loadingDel = false
        this.$message({
          type: 'error',
          message: '删除失败'
        })
        console.error('handleRowDel err: ', err)
      }
    },
    handleRowDel(row) {
      console.info(1111)
      console.info(this.adminObj)

      row.loadingDel = true
      this.$_delConfirm(
        '该条目和子部门（若有）',
        () => {
          this.delRowReq(row)
        },
        () => {
          row.loadingDel = false
        }
      )
    },
    search(obj) {
      this.getList(obj)
    },
    async getByParentId(parentId) {
      const obj = {
        pageIndex: 1,
        pageSize: 100
      }
      obj.orderBy = 'roleName'
      obj.orderByAscent = false
      obj.search = [
        {
          key: 'parentId',
          value: parentId,
          operation: 0
        }
      ]
      const {
        data: { items }
      } = await RoleSearch(obj)
      this.loadData.push(...items)
      return items
    },
    async getList(query) {
      this.loadData = []
      this.tableLoading = true
      const obj = query || {
        pageIndex: 1,
        pageSize: 10
      }
      obj.orderBy = 'createdTime'
      obj.orderByAscent = false
      if (obj.search === undefined) {
        obj.search = []
      }
      obj.search.push({
        key: 'parentId',
        value: 0,
        operation: 0
      })
      try {
        const {
          data: { items, pageIndex, count }
        } = await RoleSearch(obj)
        this.loadData.push(...items)
        this.tableData = items
        this.$nextTick(() => {
          this.$refs['clientTable'].update({ page: pageIndex, count })
          this.tableLoading = false
        })
      } catch (err) {
        console.log(err)
      }

      this.tableLoading = true
    }
  }
}
</script>

<style lang="scss" scoped>
  .el-button:focus,
  .el-button:focus:hover {
    color: #586aa6 !important;
  }
  .box:focus:hover {
    color: #fff !important;
  }
</style>
